import 'dart:math';

import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';

import 'info_button.dart';

class TableNameTest extends StatefulWidget {
  const TableNameTest({super.key});

  @override
  State<TableNameTest> createState() => _TableNameTestState();
}

class _TableNameTestState extends State<TableNameTest> {
  Database? _database;
  String? _openDbResult;
  String? _createTableResult;
  String? _insertResult;
  String? _queryResult;
  String? _updateResult;
  String? _updateResultByRaw;
  String? _updateResultByRaw1;
  String? _deleteResult;
  String? _deleteResult1;
  final String _tableName = "users";
  late String _dbName;

  @override
  void initState() {
    _dbName = "${Random().nextInt(36000)}.db";
    super.initState();
  }

  ///打开数据库
  Widget _openDbWidget() {
    return InfoButton(
      title: "打开数据库",
      info: _openDbResult,
      onTap: () async {
        try {
          _database = await openDatabase(_dbName);
          final path = await getDatabasesPath();
          setState(() {
            _openDbResult = "打开数据成功：$path";
          });
        } catch (error) {
          setState(() {
            _openDbResult = error.toString();
          });
        }
      },
    );
  }

  ///创建表
  Widget _createTableWidget() {
    return InfoButton(
      title: "创建表",
      info: _createTableResult,
      onTap: () async {
        if (_database != null) {
          try {
            await _database!.execute("CREATE TABLE $_tableName(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)");
            setState(() {
              _createTableResult = "创建表成功";
            });
          } catch (error) {
            setState(() {
              _createTableResult = error.toString();
            });
          }
        }
      },
    );
  }

  ///插入数据
  Widget _insertDataWidget() {
    return InfoButton(
      title: "插入数据",
      info: _insertResult,
      onTap: () async {
        if (_database != null) {
          try {
            final id = await _database!.insert(_tableName, {'name': 'John', 'age': 25});
            setState(() {
              _insertResult = "插入数据成功：id=$id";
            });
          } catch (error) {
            setState(() {
              _insertResult = error.toString();
            });
          }
        }
      },
    );
  }

  ///查询数据
  Widget _queryWidget() {
    return InfoButton(
      title: "查询数据",
      info: _queryResult,
      onTap: () async {
        if (_database != null) {
          final maps = await _database!.query(_tableName);
          setState(() {
            _queryResult = maps.map((map) => map.toString()).join("\n");
          });
        }
      },
    );
  }

  ///更新数据
  Widget _updateDataWidget() {
    return InfoButton(
      title: "更新数据",
      info: _updateResult,
      onTap: () async {
        if (_database != null) {
          try {
            final changeRows = await _database!.update(_tableName, {'name': 'Jack', 'age': 25}, where: 'id = ?', whereArgs: [2]);
            setState(() {
              _updateResult = "更新了$changeRows行数据";
            });
          } catch (error) {
            setState(() {
              _updateResult = error.toString();
            });
          }
        }
      },
    );
  }

  ///更新数据
  Widget _updateDataByRawWidget() {
    return InfoButton(
      title: "更新数据-raw",
      info: _updateResultByRaw,
      onTap: () async {
        if (_database != null) {
          try {
            final changeRows =
                await _database!.rawUpdate('UPDATE $_tableName SET name = ?, age = ? WHERE id = ?', ['Jack', 25, 1]);
            setState(() {
              _updateResultByRaw = "更新了$changeRows行数据";
            });
          } catch (error) {
            setState(() {
              _updateResultByRaw = error.toString();
            });
          }
        }
      },
    );
  }

  ///更新数据
  Widget _updateDataByRawWidget1() {
    return InfoButton(
      title: "更新数据-raw",
      info: _updateResultByRaw1,
      onTap: () async {
        if (_database != null) {
          try {
            final changeRows = await _database!
                .rawUpdate('UPDATE OR ROLLBACK $_tableName Set name = ?, age = ? WHERE name = ?', ['Marco', 25, "Jack"]);
            setState(() {
              _updateResultByRaw1 = "更新了$changeRows行数据";
            });
          } catch (error) {
            setState(() {
              _updateResultByRaw1 = error.toString();
            });
          }
        }
      },
    );
  }

  Widget _deleteDataByRawWidget() {
    return InfoButton(
      title: "删除数据-raw",
      info: _deleteResult,
      onTap: () async {
        if (_database != null) {
          try {
            int count = await _database!.rawDelete("DELETE FROM $_tableName WHERE id = ?", [2]);
            setState(() {
              _deleteResult = "删除成功，删除了$count行数据";
            });
          } catch (e) {
            setState(() {
              _deleteResult = e.toString();
            });
          }
        }
      },
    );
  }

  Widget _deleteDataByRawWidget1() {
    return InfoButton(
      title: "删除数据-raw-1",
      info: _deleteResult1,
      onTap: () async {
        try {
          if (_database != null) {
            int count = await _database!.rawDelete("DELETE OR ROLLBACK FROM $_tableName WHERE id = ?", [3, 4]);
            setState(() {
              _deleteResult1 = "删除成功，删除了$count行数据";
            });
          }
        } catch (e) {
          setState(() {
            _deleteResult1 = e.toString();
          });
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("表名检查"),
      ),
      body: ListView(
        children: [
          //打开数据库
          _openDbWidget(),

          //创建表
          _createTableWidget(),

          //插入数据
          _insertDataWidget(),

          //查询数据
          _queryWidget(),

          //更新数据
          _updateDataWidget(),
          //更新数据-raw
          _updateDataByRawWidget(),
          //更新数据-raw
          _updateDataByRawWidget1(),

          //删除数据
          _deleteDataByRawWidget(),
          // //删除数据
          // _deleteDataByRawWidget1(),
        ],
      ),
    );
  }
}
